package com.mall.pay.services;

import com.mall.order.OrderCoreService;
import com.mall.order.OrderQueryService;
import com.mall.order.dto.*;
import com.mall.pay.PayCoreService;
import com.mall.pay.constants.PayResultEnum;
import com.mall.pay.constants.PayReturnCodeEnum;
import com.mall.pay.dal.entitys.Payment;
import com.mall.pay.dal.persistence.PaymentMapper;
import com.mall.pay.dto.PaymentRequest;
import com.mall.pay.dto.alipay.AlipayQueryRetResponse;
import com.mall.pay.dto.alipay.AlipaymentResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import tk.mybatis.mapper.entity.Example;

import javax.validation.constraints.NotBlank;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class PayCoreServiceImpl implements PayCoreService {

    @Autowired
    PayHelper payHelper;

    @Reference
    OrderCoreService orderCoreService;

    @Autowired
    PaymentMapper paymentMapper;

    @Reference
    OrderQueryService orderQueryService;


    /*
         获取支付二维码
     */
    @Override
    public AlipaymentResponse aliPay(PaymentRequest request) {

        AlipaymentResponse alipaymentResponse = new AlipaymentResponse();
        // 1. 调用当面付Demo中的test_precreate方法，获取支付二维码
        String codeFileName = payHelper.test_trade_precreate(request);

        // 2. 判斷二维码是否获取成功
        if (codeFileName == null) {
            // 获取支付二维码失败
            alipaymentResponse.setCode(PayReturnCodeEnum.GET_CODE_FALIED.getCode());
            alipaymentResponse.setMsg(PayReturnCodeEnum.GET_CODE_FALIED.getMsg());
            log.error("PayCoreServiceImpl.aliPay:获取二维码失败");
            return alipaymentResponse;
        }

        // 初始化订单信息
        initPayment(request);

        // 2. 返回二维码，并设置响应结果信息
        alipaymentResponse.setCode(PayReturnCodeEnum.SUCCESS.getCode());
        alipaymentResponse.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());
        alipaymentResponse.setQrCode(codeFileName);
        return alipaymentResponse;
    }


    private void initPayment(PaymentRequest request) {

        // 先判断该支付信息在tb_payment中是否存在，如果存在不初始化
        String orderId = request.getTradeNo();
        Example paymentExample = new Example(Payment.class);
        paymentExample.createCriteria().andEqualTo("orderId", orderId);
        List<Payment> payments = paymentMapper.selectByExample(paymentExample);

        if (payments != null && payments.size() > 0) {
            // 如果tb_payment订单已经被初始化了，直接返回
            return;
        }


        // tb_payment订单没有被初始化，开始初始化订单
        // 1. 要在tb_payment插入一条记录，记录订单的支付信息， PayResultEnum.PAY_PROCESSING（支付处理中）
        // 根据orderId查询购物车信息
        OrderDetailRequest orderDetailRequest = new OrderDetailRequest();
        orderDetailRequest.setOrderId(orderId);
        OrderDto orderinfo = orderQueryService.getOrderDetailInfo(orderDetailRequest);

        log.info("根据orderId查询购物车信息:" + orderinfo);
        Payment payment = new Payment();
        payment.setStatus(PayResultEnum.PAY_PROCESSING.getCode());  // 支付状态
        payment.setOrderId(orderId);  // 全局唯一的订单号
        payment.setPayerUid(request.getUserId());  // 付款人id
        payment.setOrderAmount(orderinfo.getPayment());  // 订单金额
        payment.setPayerAmount(orderinfo.getPayment());   // 付款金额
        payment.setPayWay("ali_pay");  // 支付方式
        payment.setCreateTime(new Date());   // 创建时间
        int insertAffectedRows = paymentMapper.insertSelective(payment);
        log.info("在tb_payment插入一条记录:affectedRows=" + insertAffectedRows);
        log.info("在tb_payment插入一条记录:payment=" + payment);
    }

    /*
           查询订单的支付结果
     */
    @Override
    public AlipayQueryRetResponse queryAlipayRet(PaymentRequest request) {

        AlipayQueryRetResponse response = new AlipayQueryRetResponse();
        String orderId = request.getTradeNo();
        log.info("PayCoreServiceImpl.queryAlipayRet,orderId={}",orderId);

        // 调用test_trade_query方法，查询指定的订单支付结果
        boolean paySuccess = payHelper.test_trade_query(request);

        Payment payment = new Payment();

        PayOrderSuccessRequest payOrderSuccessRequest = new PayOrderSuccessRequest();
        payOrderSuccessRequest.setOrderId(orderId);

        // 判断是否支付成功
        if (paySuccess) {
            // 1. 修改tb_payment中的订单支付记录的支付结果 ->PayResultEnum.PAY_SUCCESS
            payment.setStatus(PayResultEnum.PAY_SUCCESS.getCode());
            log.info("PayCoreServiceImpl.queryAlipayRet,{}", payment);
            //  调用订单服务，完成以下功能
            orderCoreService.payOrderSuccess(payOrderSuccessRequest);
            // 2. 修改订单的状态为已支付
            // 3. 修改库存，根据OrderId，查询出所有的订单商品条目，根据每一个商品的数量，扣减锁定库存

            response.setCode(PayReturnCodeEnum.SUCCESS.getCode());
            response.setMsg(PayReturnCodeEnum.SUCCESS.getMsg());
        } else {
            // 1. 修改tb_payment中的订单支付记录的支付结果 ->PayResultEnum.PAY_FAIL
            payment.setStatus(PayResultEnum.PAY_FAIL.getCode());
            response.setCode(PayReturnCodeEnum.ORDER_HAD_NOT_PAY.getCode());
            response.setMsg(PayReturnCodeEnum.ORDER_HAD_NOT_PAY.getMsg());
        }

        payment.setUpdateTime(new Date());
        Example paymentExample = new Example(Payment.class);
        paymentExample.createCriteria().andEqualTo("orderId", orderId);
        paymentMapper.updateByExampleSelective(payment, paymentExample);
        // 返回相应的response

        log.info("PayCoreServiceImpl.queryAlipayRet,{}", response);
        return response;
    }
}
